<template>
  <div class="">
    <div>
        <div v-if="isLoading" class="loading">
          <!-- 加载动画 -->
          <div class="center">
          <div class="spinner"></div>
          <div class="icon-wrapper">
            <!-- 安全盾牌图标 -->
          <!-- <div class="icon"> -->
            <svg  width="30" height="30"  viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 1.5L3 4.5V13.5C3 18.4711 7.02891 22.5 12 22.5C16.9711 22.5 21 18.4711 21 13.5V4.5L12 1.5ZM19.3125 13.5C19.3125 17.5383 16.0383 20.8125 12 20.8125C7.96172 20.8125 4.6875 17.5383 4.6875 13.5V5.76562L12 3.1875L19.3125 5.76562V13.5Z" fill="#6F6F6F"/>
                <path d="M8.86919 11.1351C8.79098 11.0566 8.69803 10.9942 8.59567 10.9517C8.49331 10.9092 8.38355 10.8873 8.2727 10.8873C8.16185 10.8873 8.05209 10.9092 7.94973 10.9517C7.84737 10.9942 7.75442 11.0566 7.67621 11.1351C7.59765 11.2133 7.53531 11.3063 7.49278 11.4087C7.45024 11.511 7.42834 11.6208 7.42834 11.7316C7.42834 11.8425 7.45024 11.9522 7.49278 12.0546C7.53531 12.157 7.59765 12.2499 7.67621 12.3281L10.709 15.3609L10.7583 15.4101C10.8322 15.4842 10.9201 15.543 11.0168 15.5832C11.1135 15.6233 11.2172 15.6439 11.3219 15.6439C11.4266 15.6439 11.5303 15.6233 11.627 15.5832C11.7238 15.543 11.8116 15.4842 11.8856 15.4101L17.1239 10.1719C17.198 10.0979 17.2568 10.01 17.2969 9.91332C17.337 9.81659 17.3577 9.71291 17.3577 9.6082C17.3577 9.50349 17.337 9.39981 17.2969 9.30309C17.2568 9.20636 17.198 9.1185 17.1239 9.04453L17.0583 8.97891C16.9843 8.9048 16.8964 8.846 16.7997 8.80588C16.703 8.76577 16.5993 8.74512 16.4946 8.74512C16.3899 8.74512 16.2862 8.76577 16.1895 8.80588C16.0928 8.846 16.0049 8.9048 15.9309 8.97891L11.3208 13.5867L8.86919 11.1351Z" fill="#6F6F6F"/>
                <rect x="-855.5" y="-110.5" width="2535" height="1373" rx="39.5" stroke="#EF5533"/>
                </svg>
          <!-- </div> -->
          </div>
        </div>
          <h3>正在进行账号环境检测</h3>
        </div>
        <div v-else>
          <!-- 组件内容 -->
          <GhNavBar title="修改密码"  /> 
          <div class="updatePage">
            <van-form autocomplete="off"  ref="form">
                <van-field
                v-model="account"
                name="account"
                placeholder="请输入手机号"
                disabled
                type="tel">
                <template #label>
                     <span style="color: black;">手机号码</span>
                  </template>
              </van-field>
              <van-field  v-model="code" placeholder="短信验证码"  required :rules="userFormRules.code" label="验证码">
                      <template #button>
                        <span class="btn-send"  :class="{ active: time> 0 }" @click="onSend" > 
                          {{ time> 0 ? `${time}s后再次发送` :'发送验证码' }}
                        </span>
                      </template>
              </van-field>
              <van-field
              name="oldPassword"
              v-model="oldPassword"
              label="旧密码"
              placeholder="请输入原密码"
              required
              :rules="userFormRules.password"
              type="password">
                </van-field>
             <van-field
              name="newPassword" 
               v-model="newPassword" 
                label="新密码" 
                placeholder="至少一个字母、一个数字和一个字符"
                required
                :rules="userFormRules.password"
                 type="password">
             </van-field>
            <van-field 
            name="verifyNewPassword" 
            v-model="verifyNewPassword"
            label="确认密码"
            required
             placeholder="请再次输入密码"
             :rules="userFormRules.password"
              type="password"> 
            </van-field>
        </van-form>
            <van-cell-group  v-if="passwordsMatch && newPassword !== '' && verifyNewPassword !== ''">
                <van-cell title="密码不一致" class="cell-with-icon">
                  <template #right-icon>
                    <van-icon name="clear"></van-icon>
                  </template>
                </van-cell>
              </van-cell-group>
              <van-cell-group v-else-if="newPassword !== '' && verifyNewPassword!== ''">
                <van-cell title="密码一致" class="cell-with-icon">
                  <template #right-icon>
                    <van-icon name="success"></van-icon>
                  </template>
                </van-cell>
              </van-cell-group>
               <!-- 兜底 校验 native-type -->
               <van-button native-type="submit" @click="onSubmit" :loading="isRegistering"  :disabled="passwordsMatch.value|| newPassword === '' || verifyNewPassword === ''"  block round type="primary">
                确认修改
              </van-button>
         
            </div>
        </div>
      </div>

  </div>
</template>

<script setup>
import {ref,onMounted,computed} from "vue"
import GhNavBar from '@/components/gh-nav-bar.vue'
import { getIdentCode ,updatePassword} from '@/services/user'
import {useRouter,useRoute} from 'vue-router'
import { Toast, Dialog } from 'vant';
import { useUserStore } from '@/stores'
import 'vant/es/toast/style'


//跳转路由使用
const router=useRouter();
// 获取路由参数
const route = useRoute()


const passwordRule=ref([{
    required:true,
    message:'密码不能为空'
},
{
    pattern:/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
    message:'密码格式错误'
}])
const codeRule =ref([{
          required: true,
          message: '验证码不能为空'
        }, {
          pattern: /^\d{6}$/,
          message: '验证码格式错误'
        }])
// 将验证规则对象暴露给模板
const userFormRules = computed(() => {
  return {
    code: codeRule.value,
    password:passwordRule.value
  };
});

//定义密码不一致的显示
const passwordsMatch=computed(()=> {
      return newPassword.value!==verifyNewPassword.value;
    })

const isLoading =ref(true)
onMounted(()=>{
    setTimeout(() => {
    isLoading.value= false;
    }, 1000); // 1秒后隐藏加载页面
})

const account=ref(JSON.parse(localStorage.getItem('gh-user')).user.userData.account)
const code=ref('')
const oldPassword=ref('')
const newPassword=ref('')
const verifyNewPassword=ref('')
//定义验证码发送倒计时间
const time=ref(0);
// const time2=ref(0);
let timer;
//定义发送验证码的函数
const onSend =async()=>{
       if(!account.value){
           Toast('请先输入手机号！')
           return
       }
       
       if(time.value>0)return;
      const res=await getIdentCode(account.value).then((response)=>{
        return response
    }).catch((error)=>{
     return error
    })
       console.log(res.data)
       Toast('发送成功')
       time.value = 60
       // 开启倒计时
       if (timer) clearInterval(timer)
        timer = window.setInterval(() => {
             time.value--
             if (time.value <= 0) {clearInterval(timer)}
           }, 1000)
}
const isRegistering = ref(false);
//定义确认修改密码的逻辑
const onSubmit=async()=>{
    isRegistering.value = true;
    if(passwordsMatch.value){
        Toast('输入两次密码不一致')
        newPassword.value=''
        verifyNewPassword.value=''
        isRegistering.value=false
        return
    }
    setTimeout(async() => {
      
    const formData=new FormData();
    formData.append('account',account.value)
    formData.append('code',code.value)
    formData.append('oldPassword',oldPassword.value)
    formData.append('newPassword',newPassword.value)
    formData.append('verifyNewPassword',verifyNewPassword.value)
    // for (const pair of formData.entries()) {
    //       console.log('表单数据：',pair[0], pair[1]);
    //     }
   const res =await updatePassword(formData).then((response)=>{
        return response
    }).catch((error)=>{
     return error
    })
       console.log(res)
    if(res.status!==201){
     if(res.response.status==402){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
     }
     if(res.response.status==403){
        const toastMessage=res.response.data.error
        Toast.fail(toastMessage)
        isRegistering.value=false;
        return
     }
     else{
        Toast.fail('修改密码失败')
        isRegistering.value=false;
        return
     }
    }
    Toast('修改成功,请重新登录')
    router.push('/login')
    isRegistering.value=false;
   }, 1000);
    
}
</script>

<style lang="scss" scoped>

.loading {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  flex-direction: column;
  .center{
   position: relative;
    .spinner {
       position: relative;
       width: 60px;
       height: 60px;
       top: 0;
       left: 0;
       /* margin: 0 auto; */
       border-radius: 100%;
       border: 3px solid var(--gh-tip);
       border-top-color:var(--gh-primary);
       animation: spin 1s linear infinite;
     }
   .icon-wrapper {
      position: absolute;
      top:50%;
      left: 50%;
      transform: translate(-50%,-50%);
      display: flex;
      justify-content: center;
      align-items: center;
      /* width: 50px;
      height: 50px; */
    }
  }
      
      h3{
          display: inline-block;
          font-family: '宋体';
          margin-top: 40px;
      }
}
.updatePage{
    padding-top: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .van-button{
       width: 90%;
       /* left: 50%;
       transform: translate(-50%); */
        margin-top: 15px;
        font-size: '宋体';
    }
    .btn-send{
      color: var(--gh-primary);
      &.active {
        color: rgba(22, 194, 163, 0.5);
      }
    }
   
        /* display: flex; */
        .cell-with-icon {
        font-size: 14px;
        color: var(--gh-primary);
        margin-right: 5px;
        font-family: '楷体';
        display: flex;
        align-items: center; /* 使图标垂直居中 */
        .van-cell__title {
              flex: 1; /* 将标题文字占满剩余的空间 */
          }
    
    }
   

}


@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

</style>
